package com.ruoyi.system.controlle;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.PersonnelInformationUserService;
import com.ruoyi.system.service.fileDataService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.*;

/**
 *描述 ：人员信息
 *@author senyuan.li
 *@date 19:23 2024/3/31
 *@param 
 *@return 
 **/
@Controller
@RequestMapping("/personnelInformationUser")
public class PersonnelInformationUserController extends BaseController
{

    @Autowired
    private PersonnelInformationUserService PersonnelInformationUserService;



    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestBody PersonnelInformationUser personnelInformationUser)
    {
        startPage(personnelInformationUser.getPageNum(),personnelInformationUser.getPageSize());
        List<PersonnelInformationUser> list = PersonnelInformationUserService.selectFileDataList(personnelInformationUser);
        return getDataTable(list);
    }



    @PostMapping("/add")
    @ResponseBody
    public Map addSave(@RequestBody PersonnelInformationUser personnelInformationUser)
    {

        Map map=new HashMap();
        PersonnelInformationUser personnelinformationuser= PersonnelInformationUserService.getWorknumber(personnelInformationUser.getWorknumber());
        if(personnelinformationuser!=null)
        {

            map.put("error","工号重复");
            map.put("code","5001");
            return map;
        }else{
            PersonnelInformationUserService.insertFileData(personnelInformationUser);
            map.put("success","成功");
            map.put("code","200");
            return map;
        }



    }

    @GetMapping("/remove")
    @ResponseBody
    public AjaxResult remove( Integer id)
    {

        return toAjax(PersonnelInformationUserService.deleteUserByIds(id));
    }


    @PostMapping("/edit")
    @ResponseBody
    public Map editSave(@RequestBody PersonnelInformationUser personnelInformationUser) {
        Map map = new HashMap();
        PersonnelInformationUser personnelinformationuser = PersonnelInformationUserService.getWorknumber(personnelInformationUser.getWorknumber());
        if (personnelinformationuser == null) {
            int i = PersonnelInformationUserService.editSave(personnelInformationUser);
            map.put("success", "成功");
            map.put("code", "200");
            return map;
        }else{
        if (personnelInformationUser.getWorknumber2().equals(personnelinformationuser.getWorknumber())) {
            int i = PersonnelInformationUserService.editSave(personnelInformationUser);
            map.put("success", "成功");
            map.put("code", "200");
            return map;
        } else {
            if (personnelinformationuser != null) {

                map.put("error", "工号重复");
                map.put("code", "5001");
                return map;
            } else {
                int i = PersonnelInformationUserService.editSave(personnelInformationUser);
                map.put("success", "成功");
                map.put("code", "200");
                return map;
            }
        }
        }
    }





  /**
   *描述 ：人员信息导入
   *@author senyuan.li
   *@date 21:59 2024/4/2
   *@param [file, updateSupport]
   *@return com.ruoyi.common.core.domain.AjaxResult
   **/
  @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<PersonnelInformationUser> util = new ExcelUtil<PersonnelInformationUser>(PersonnelInformationUser.class);
       /* List<PersonnelInformationUser> userList = util.importExcelPersonnelln(file.getInputStream());
        System.out.println(userList);*/
        List<PersonnelInformationUser> list=new ArrayList<PersonnelInformationUser>();
        if (file == null) {
            return AjaxResult.success("文件不能为空");
        }
        String fileName = file.getOriginalFilename();
        long size = file.getSize();
        if (StringUtils.isBlank(fileName) || size == 0 || !fileName.endsWith("xlsx") && !fileName.endsWith("xls") && !fileName.endsWith("xlsm")) {
            return AjaxResult.success("格式错误，请确认后上传");
        }
        Workbook wb;
        File file1 = null;
        try {
            if (file.equals("") || file.getSize() <= 0) {
                file = null;
            } else {
                InputStream ins = file.getInputStream();
                file1 = new File(file.getOriginalFilename());
                util.getInputStream(ins, file1);
                ins.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        try {
            FileInputStream fis = new FileInputStream(file1);
            //将文件二进制流保存到数据库

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bos.flush();

            wb = new HSSFWorkbook(fis);
            bos.close();
            fis.close();
            Sheet xssfSheet = wb.getSheetAt(0);
            Row hrow;
            Cell hcell;
            int physicalNumberOfRows = xssfSheet.getPhysicalNumberOfRows();
              Map map=new HashMap();
            for (int i = 1; i < physicalNumberOfRows; i++) {
                PersonnelInformationUser personnelinformationUser=new PersonnelInformationUser();
                hrow = xssfSheet.getRow(i);
                hcell = hrow.getCell(0);
                personnelinformationUser.setName(hcell.toString());
                if(StringUtils.isEmpty(hcell.toString())){
                    break;
                }

                hcell = hrow.getCell(1);
                personnelinformationUser.setDuties(hcell.toString());
                hcell = hrow.getCell(2);
                if(StringUtils.isNotEmpty(hcell.toString())){
                    personnelinformationUser.setWorknumber(hcell.toString());
                    if(map.get(hcell.toString())==null){
                        map.put(hcell.toString(),hcell.toString());
                    }else{
                        return AjaxResult.success("工号重复");
                    }


                }else{
                    return AjaxResult.success("工号不能为空");
                }

                hcell = hrow.getCell(3);
                personnelinformationUser.setPhone(hcell.toString());
                hcell = hrow.getCell(4);
                personnelinformationUser.setPhone2(hcell.toString());
                hcell = hrow.getCell(5);
                personnelinformationUser.setPhone3(hcell.toString());
                list.add(personnelinformationUser);
            }





        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(list);




        for (int i = 0; i < list.size(); i++) {
            PersonnelInformationUser personnelInformationUser = list.get(i);
            PersonnelInformationUser personnelinformationuser = PersonnelInformationUserService.getWorknumber(personnelInformationUser.getWorknumber());
            if(personnelinformationuser!=null){
                return AjaxResult.success("工号重复("+personnelinformationuser.getWorknumber()+")");
            }
        }

        PersonnelInformationUserService.insertList(list);
        return AjaxResult.success("成功");
    }

    @RequestMapping("/downLoadTemplate")
    public void downLoadTemplate() {
        HttpServletResponse resp = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        PersonnelInformationUserService.downLoadTemplate(resp);
    }
    
    /**
     *描述 ：在值班人员列表中选择多个人员后，点击“导入签到表”，进入下面界面。
     *@author senyuan.li
     *@date 20:45 2024/5/10
     *@param 
     *@return 
     **/
    @PostMapping("/addSignin")
    @ResponseBody
    public Map addSignin(@RequestBody List<PersonnelInformationUserSignin> list) {
        Map map = new HashMap();
        if(list.size()>0){
            PersonnelInformationUserService.deletePersonnelInformationUserSignin(list.get(0).getBatchNumber());
            PersonnelInformationUserService.addaddSignin(list);
        }

        map.put("success", "成功");
        map.put("code", "200");
        return map;
    }


  /*
   *描述 ：查询签到的暂存数据
   *@author senyuan.li
   *@date 21:40 2024/5/10
   *@param []
   *@return com.ruoyi.common.core.page.TableDataInfo
   **/
    @GetMapping("/getPersonnelInformationUser")
    @ResponseBody
    public TableDataInfo getPersonnelInformationUser()
    {
        List<PersonnelInformationUserSignin> list = PersonnelInformationUserService.getPersonnelInformationUser();
        return getDataTable(list);
    }

   /**
    *描述 ：取消或者结束  传入批次号
    *@author senyuan.li
    *@date 21:41 2024/5/10
    *@param [list]
    *@return java.util.Map
    **/
    @PostMapping("/updateSigninState")
    @ResponseBody
    public Map updateSigninState(@RequestBody List<PersonnelInformationUserSignin> list) {
        Map map = new HashMap();


        if(list.size()>0) {
            PersonnelInformationUserService.deletePersonnelInformationUserSignin(list.get(0).getBatchNumber());

            if ("结束".equals(list.get(0).getState())) {
                PersonnelInformationUserService.addaddSignin(list);
            }
        }
                   map.put("success", "成功");
                   map.put("code", "200");
        return map;
    }

    
    /*
     *描述 ：签到完成列表
     *@author senyuan.li
     *@date 21:47 2024/5/10
     *@param 
     *@return 
     **/

    @PostMapping("/getPersonnelInformationUserlist")
    @ResponseBody
    public TableDataInfo getPersonnelInformationUserlist(@RequestBody PersonnelInformationUserSignin personnelinformationusersignin)
    {
        startPage(personnelinformationusersignin.getPageNum(),personnelinformationusersignin.getPageSize());
        List<PersonnelInformationUserSignin> list = PersonnelInformationUserService.getPersonnelInformationUserlist(personnelinformationusersignin);
        return getDataTable(list);
    }

    @GetMapping("/personnelInformationUserSigninRemove")
    @ResponseBody
    public AjaxResult personnelInformationUserSigninRemove( String batchNumber)
    {
        return toAjax(PersonnelInformationUserService.deletePersonnelInformationUserSignin(batchNumber));
    }




    @ResponseBody
    @RequestMapping(value = "/downloadSignin", method = RequestMethod.GET)
    public void downloadSignin(String batchNumber, HttpServletResponse response) throws Exception{
        Calendar instance = Calendar.getInstance();
        HashMap<String, ByteArrayOutputStream> hashMap = new HashMap<>();
        //查询借货单数据
        String templateName = "签到表.xls";
        StringBuilder builder = new StringBuilder();
       List<PersonnelInformationUserSignin> list =  PersonnelInformationUserService.getSigninObj(batchNumber);
        ApplicationHome h = new ApplicationHome(getClass());
        String dirPath = h.getSource().toString();
        String fileName =templateName;
        InputStream input = ClassUtils.getDefaultClassLoader().getResourceAsStream("static/" + templateName);
        Workbook wbs =readExcelTemplate(fileName);
        Sheet sheet = wbs.getSheetAt(0);
        Row row = null;
        Cell cell = null;
        row = sheet.getRow(1);
        Cell valueCell1 = row.getCell(2);
        valueCell1.setCellValue(list.get(0).getFaultName());
        row = sheet.getRow(2);
        cell = row.getCell(2);
        cell.setCellValue(list.get(0).getOverviewSituation());
        int rowNumber=4;
        for (int i = 0; i < list.size(); i++) {
            PersonnelInformationUserSignin kitordervm2 = list.get(i);
            //随货单业务处理

            row = sheet.getRow(rowNumber);
            cell = row.getCell(0);
            cell.setCellValue(i+1);
            cell = row.getCell(2);

            cell.setCellValue(kitordervm2.getWorknumber());
            cell = row.getCell(4);

            cell.setCellValue(kitordervm2.getName());
            cell = row.getCell(6);

            cell.setCellValue(kitordervm2.getNotificationTime());
            cell = row.getCell(9);

            cell.setCellValue(kitordervm2.getOnSiteTime());
            rowNumber++;
        }
        // sheet.addMergedRegion(cra);
        CellStyle style = wbs.createCellStyle();
//创建字体样式
        Font font = wbs.createFont();
//true为加粗，默认为不加粗
        style.setWrapText(true);//设置自动换行
        font.setBold(true);
        font.setFontHeightInPoints((short) 10);//字号
        style.setFont(font);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        response.setContentType(response.getContentType());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(("签到表.xls").getBytes(), StandardCharsets.ISO_8859_1));
        wbs.write(baos);
        byte[] bytes = baos.toByteArray();
        response.setHeader("Content-Length", String.valueOf(bytes.length));
        BufferedOutputStream bos = null;
        bos = new BufferedOutputStream(response.getOutputStream());
        bos.write(bytes);
        bos.close();
        baos.close();
        wbs.close();
    }

    public static Workbook readExcelTemplate(String templateName) throws IOException, GeneralSecurityException, InvalidFormatException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
/*        String realPath = request.getSession().getServletContext().getRealPath("/");
        File file = new File(templateName);
        InputStream is = new FileInputStream(file);*/
        InputStream is = ClassUtils.getDefaultClassLoader().getResourceAsStream("static/" + templateName);

        Workbook wbs = WorkbookFactory.create(is);
        is.close();
        return wbs;
    }
}